import { createRouter, createWebHistory } from 'vue-router'

import Home from './views/Home.vue'
import PostDetail from './components/PostDetail.vue'
import Login from './views/Login.vue'
import Message from './components/createMessage'
import { axiosInstance } from './axiosDefaults'
import store from './store'

const routerHistory = createWebHistory()
const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { redirectAlreadyLogin: true }
    },
    {
      path: '/columnDetail/:id',
      name: 'columnDetail',
      component: () => import('./components/ColumnDetail.vue')
    },
    {
      path: '/signup',
      name: 'signup',
      component: () => import('./views/Signup.vue'),
      meta: { redirectAlreadyLogin: true }
    },
    {
      path: '/create',
      name: 'createPost',
      component: () => import('./components/CreatePost.vue'),
      meta: { requireLogin: true }
    },
    {
      path: '/postDetail/:id',
      name: 'postDetail',
      component: PostDetail,
      meta: { requireLogin: true }
    }
  ]
})

router.beforeEach((to, from, next) => {
  const { isLogin } = store.state.user
  const { token } = store.state
  const { redirectAlreadyLogin, requireLogin } = to.meta
  if (!isLogin) {
    if (token) {
      axiosInstance.defaults.headers.common.Authorization = `Bearer ${token}`
      store.dispatch('usercurrent').then(() => {
        if (redirectAlreadyLogin) {
          next('/')
        } else {
          next()
        }
      }).catch(err => {
        store.commit('logout')
        console.error(err)
        Message('请求用户信息失败', 'error')
        next('/login')
      })
    } else {
      if (requireLogin) {
        next('/login')
      } else {
        next()
      }
    }
  } else {
    if (redirectAlreadyLogin) {
      next('/')
    } else {
      next()
    }
  }
})
export default router
